import React, { useState, useEffect } from 'react';
import { List, Image, Space, Button, Empty, Toast, Avatar, Card, Dialog, DotLoading } from 'antd-mobile';
import { AddOutline, RightOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import { checkLoginStatus, getMyTravels } from '../../services/api';
import { getCurrentUser, logout } from '../../services/auth'; // 导入获取用户信息和退出登录函数
import styles from './index.module.css'; // 导入样式文件

interface MyTravelItem {
  id: string;
  title: string;
  cover: string;
  date: string;
  location: string;
  status: 'pending' | 'rejected' | 'approved';
  isDeleted?: boolean;
}

const mockData: MyTravelItem[] = [
  {
    id: '1',
    title: '我的重庆之旅，探索山城的魅力与美食',
    cover: 'https://picsum.photos/300/200?random=4',
    date: '2023-08-05',
    location: '重庆',
    status: 'approved'
  },
  {
    id: '2',
    title: '三亚海滩度假，享受阳光与海浪',
    cover: 'https://picsum.photos/300/200?random=5',
    date: '2023-09-15',
    location: '海南三亚',
    status: 'pending'
  },
  {
    id: '3',
    title: '西藏朝圣之旅，感受雪域高原的神秘',
    cover: 'https://picsum.photos/300/200?random=6',
    date: '2023-10-01',
    location: '西藏拉萨',
    status: 'rejected'
  },
  {
    id: '4',
    title: '北京故宫一日游，探索古代皇家建筑',
    cover: 'https://picsum.photos/300/200?random=7',
    date: '2023-07-20',
    location: '北京',
    status: 'approved',
    isDeleted: true
  }
];

const getStatusText = (status: MyTravelItem['status'], isDeleted?: boolean) => {
  if (isDeleted) {
    return '已删除';
  }

  switch (status) {
    case 'approved':
      return '已通过';
    case 'pending':
      return '审核中';
    case 'rejected':
      return '未通过';
    default:
      return '';
  }
};

const getStatusColor = (status: MyTravelItem['status'], isDeleted?: boolean) => {
  if (isDeleted) {
    return '#909399';
  }

  switch (status) {
    case 'approved':
      return '#52c41a';
    case 'pending':
      return '#faad14';
    case 'rejected':
      return '#f5222d';
    default:
      return '';
  }
};

const MyTravelsPage: React.FC = () => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(true);
  const [isLoggedIn, setIsLoggedIn] = useState(false); // 添加登录状态
  const [userData, setUserData] = useState<any>(null); // 添加用户数据状态
  const [travels, setTravels] = useState<MyTravelItem[]>([]); // 添加游记列表状态

  useEffect(() => {
    const checkAuthAndLoad = async () => {
      try {
        const loggedIn = await checkLoginStatus();
        setIsLoggedIn(loggedIn);

        if (loggedIn) {
          // 获取用户信息
          try {
            const userInfo = await getCurrentUser();
            if (userInfo) {
              setUserData({
                nickname: userInfo.nickname,
                username: userInfo.username,
                avatar: userInfo.avatar || 'https://picsum.photos/200?random=1'
              });

              // 获取游记列表
              const myTravels = await getMyTravels(userInfo.id);
              setTravels(myTravels);
            }
          } catch (error) {
            console.error('获取用户信息失败:', error);
            Toast.show({
              icon: 'fail',
              content: '获取用户信息失败',
            });
          }
        }
        setIsLoading(false);
      } catch (error) {
        console.error('检查登录状态失败:', error);
        setIsLoading(false);
      }
    };

    checkAuthAndLoad();
  }, [navigate]);

  // 处理退出登录
  const handleLogout = () => {
    Dialog.confirm({
      content: '确定要退出登录吗？',
      onConfirm: async () => {
        try {
          await logout();
          setIsLoggedIn(false);
          setUserData(null);
          Toast.show({
            icon: 'success',
            content: '已退出登录',
          });
        } catch (error) {
          console.error('退出登录失败:', error);
          Toast.show({
            icon: 'fail',
            content: '退出登录失败，请重试',
          });
        }
      },
    });
  };

  // 如果正在检查登录状态或加载数据，可以显示加载指示器
  if (isLoading) {
    return (
      <div className={styles.loadingContainer}>
        <DotLoading color='primary' />
        <span className={styles.loadingText}>加载中</span>
      </div>
    );
  }

  return (
    <div className={styles.myPage}>
      {isLoggedIn ? (
        // 已登录状态
        <>
          {/* 用户信息卡片 */}
          <Card className={styles.userCard}>
            <div className={styles.userInfo}>
              <Avatar src={userData?.avatar} style={{ '--size': '68px' }} />
              <div className={styles.userMeta}>
                <p className={styles.userName}>
                  用户名：{userData?.username || '无'}，昵称：{userData?.nickname || '无'}
                </p>
              </div>
            </div>
            <Button
              className={styles.logoutButton}
              onClick={handleLogout}
              size='small'
              fill='outline'
            >
              退出登录
            </Button>
          </Card>

          {/* 我的游记标题 */}
          <div className={styles.sectionHeader}>
            <h2 className={styles.sectionTitle}>我的游记</h2>
            <Button
              color='primary'
              size='small'
              onClick={() => navigate('/publish')}
            >
              <AddOutline fontSize={14} /> 写游记
            </Button>
          </div>

          {/* 游记列表 */}
          {travels.length > 0 ? (
            <List className={styles.travelsList}>
              {travels.map(item => (
                <List.Item
                  key={item.id}
                  onClick={item.isDeleted ? undefined : () => navigate(`/detail/${item.id}`)}
                  prefix={
                    <Image
                      src={item.cover}
                      style={{ borderRadius: 8, width: 120, height: 80 }}
                      fit='cover'
                      className={item.isDeleted ? styles.imageDeleted : ''}
                    />
                  }
                  arrow={!item.isDeleted ? <RightOutline /> : null}
                  extra={
                    <span className={styles.statusTag} style={{
                      color: getStatusColor(item.status, item.isDeleted),
                      borderColor: getStatusColor(item.status, item.isDeleted)
                    }}>
                      {getStatusText(item.status, item.isDeleted)}
                    </span>
                  }
                  description={
                    <Space direction='vertical' style={{ fontSize: '14px' }}>
                      <span className={styles.travelDate}>{item.date}</span>
                      <span className={styles.travelLocation}>{item.location}</span>
                    </Space>
                  }
                  className={item.isDeleted ? styles.itemDeleted : ''}
                >
                  <div className={styles.travelTitle}>{item.title}</div>
                </List.Item>
              ))}
            </List>
          ) : (
            <Empty
              style={{ padding: '64px 0' }}
              imageStyle={{ width: 128 }}
              description="暂无游记，快去创建吧"
            />
          )}
        </>
      ) : (
        // 未登录状态
        <div className={styles.notLoggedIn}>
          <div className={styles.loginPrompt}>
            <h2>您还未登录</h2>
            <p>登录后可以查看和管理您的游记</p>
            <div className={styles.authButtons}>
              <Button
                color='primary'
                block
                onClick={() => navigate('/auth/login')}
                className={styles.loginButton}
              >
                登录
              </Button>
              <Button
                fill='outline'
                block
                onClick={() => navigate('/auth/register')}
                className={styles.registerButton}
              >
                注册
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MyTravelsPage;